import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tooltip,
  Rate,
  Checkbox,
  Tabs,
} from 'antd';
import Headline from '@/components/Headline';
import StandardTable from '@/components/StandardTable';
import IconButton from '@/components/IconButton';

import ProductRangeForm from '@/components/ProductRange';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import RegionSelectModal from '../../../Base/Region/RegionSelectModal';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';

import styles from './Manage.less';
import detailStyles from './index.less';
import Link from 'umi/link';
import { stringify } from 'querystring';
import { REGION_ADDRESS_TYPE, REGION_TYPE, SERVICE_STATUS } from '@/Constants';
import api from '@/api';
import { maxLength } from '@/utils/form';
import arrowImg from '@/assets/imgs/long_arrow@2x.png';

const FormItem = Form.Item;
const { TextArea, Search } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;

@Form.create()
class CreateForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      key: 0,
      allRangeList: [],
      allRegionArray: [],
      childComponent: [],
    };
  }

  componentDidMount() { }
  componentWillReceiveProps(nextProps) {
    this.setState({
      childComponent: [],
    });
  }

  // 模态框里的增加线路按钮
  addRange = () => {
    const { viewId, type } = this.props;
    const { key, allRangeList } = this.state;
    message.destroy();
    if (allRangeList.length === 1) {
      if (!allRangeList[0]['currentRegion']) {
        message.warning('请先添加上一条范围！');
        return;
      }
    } else if (allRangeList.length > 1) {
      if (!allRangeList[allRangeList.length - 1]['currentRegion']) {
        message.warning('请先添加上一条范围！');
        return;
      }
    }
    let currentKey = key;
    currentKey++;
    let currentList = allRangeList;
    this.setState({ key: currentKey });
    const params = {
      viewId,
      type,
      key: currentKey,
      keyIndex: currentKey,
    };
    currentList.push(params);
    this.setState({ allRangeList: currentList });
  };
  // 模态框里线路后的删除按钮
  removeRange = key => {
    Modal.confirm({
      title: '删除范围',
      content: '确定删除此范围吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const { allRangeList, allRegionArray, childComponent } = this.state;
        let currentList = allRangeList;
        let currentArray = allRegionArray;
        let currentChild = childComponent;
        if (key === 1) {
          currentChild = [];
        } else {
          currentChild.splice(key - 1);
        }
        currentList = currentList.filter(val => val.keyIndex !== key);
        currentArray = currentArray.filter(val => val.keyIndex !== key);
        this.setState({
          allRangeList: currentList,
          allRegionArray: currentArray,
          childComponent: currentChild,
        });
      },
    });
  };

  judgeInArray = (index, arr) => arr.findIndex(val => val.keyIndex === index);

  // 子组件选中起始点后传值给父组件
  handleTempStorage = value => {
    const { allRegionArray, allRangeList, childComponent } = this.state;
    let allArray = allRegionArray;
    let rangArray = [];
    let childArray = [];
    const idx = this.judgeInArray(value.keyIndex, allArray);
    if (idx > -1) {
      allArray[idx] = { ...allArray[idx], ...value };
    } else {
      allArray.push(value);
    }

    allArray.length &&
      allArray.map(val => {
        const params = {
          isUpdate: true,
          keyIndex: val.keyIndex,
          key: val.keyIndex,
          viewId: allRangeList.length && allRangeList[0].viewId,
          type: allRangeList.length && allRangeList[0].type,
          currentRegion: {
            startItems: val.regionItems,
            endItems: val.destinationRegionItems,
          },
        };
        rangArray.push(params);
        const arr = childComponent.filter(
          item => item && item.props && item.props.keyIndex === val.keyIndex
        );
        childArray = [...childArray, ...arr];
      });
    if (allRangeList.length > allRegionArray.length) {
      rangArray[allRangeList.length - 1] = allRangeList[allRangeList.length - 1];
    }
    this.setState({
      allRangeList: rangArray,
      allRegionArray: allArray,
      childComponent: childArray,
    });
  };

  getChildFun() {
    const { childComponent } = this.state;
    let passArray = [];
    childComponent.length &&
      childComponent.map(val => {
        if (val.validateAddress()) {
          passArray.push(0);
        } else {
          passArray.push(1);
        }
      });
    return passArray;
  }
  // 获取子组件
  onRef = ref => {
    const { childComponent } = this.state;
    let array = childComponent;
    array.push(ref);
    this.setState({
      childComponent: array,
    });
  };

  render() {
    const { modalVisible, form, handleAdd, handleModalVisible, match, viewId, type } = this.props;
    const { allRegionArray, allRangeList } = this.state;
    let isAirProduct =
      (viewId === 'product' && type === '1') || (viewId === 'service' && type === 'AIR');
    const Transtype = isAirProduct ? REGION_ADDRESS_TYPE.AIR_PORT : REGION_ADDRESS_TYPE.AREA;
    const okHandle = () => {
      if (allRegionArray && allRegionArray.length === 0) {
        message.error('未添加范围！', 10);
        return;
      }
      const passFlag = this.getChildFun().every(val => val === 0);
      if (!passFlag) return;
      let params = [];
      allRegionArray.length &&
        allRegionArray.map(item => {
          let originItems = [];
          let destinationItems = [];
          originItems = item.regionItems && item.regionItems.map(item => ({ areas: item }));
          destinationItems =
            item.destinationRegionItems &&
            item.destinationRegionItems.map(item => ({ areas: item }));
          params.push({
            startItems: originItems,
            endItems: destinationItems,
            regionAddressType: Transtype,
          });
        });
      handleAdd(params).then(res => {
        if (res.errorCode === 0) {
          message.success('添加成功')
          this.setState({
            key: 0,
            allRangeList: [],
            allRegionArray: [],
          });
        }
      });
    };

    // 模态框里的取消按钮
    const cancelHandle = () => {
      handleModalVisible();
      this.setState({
        key: 0,
        allRangeList: [],
        allRegionArray: [],
      });
    };
    return (
      <Modal
        width={900}
        maskClosable={false}
        keyboard={false}
        destroyOnClose
        title="添加范围"
        visible={modalVisible}
        onOk={okHandle}
        onCancel={cancelHandle}
      >
        <Row type="flex" justify="start">
          <Col span={7}>
            <div className={styles.startOrEndStyle}>起点</div>
          </Col>
          <Col span={6} />
          <Col span={7}>
            <div className={styles.startOrEndStyle}>终点</div>
          </Col>
        </Row>
        {allRangeList.length > 0 &&
          allRangeList.map((val, index) => (
            <>
              <Row type="flex" justify="start">
                <Col span={23}>
                  <ProductRangeForm
                    {...val}
                    handleSaveRange={this.handleTempStorage}
                    onRef={this.onRef}
                  />
                </Col>
                <Col span={1}>
                  <IconButton
                    style={{ position: 'absolute', top: 4 }}
                    title="删除此范围"
                    icon="icon-delete"
                    onClick={() => this.removeRange(val.keyIndex)}
                  />
                </Col>
              </Row>
            </>
          ))}
        <Row type="flex" justify="center">
          <Form.Item>
            <IconButton icon="icon-add" title="添加范围" onClick={this.addRange} />
          </Form.Item>
        </Row>
      </Modal>
    );
  }
}

@Form.create()
class UpdateForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      key: 0,
      allRangeList: [],
      allRegionArray: [],
      childComponent: [],
    };
  }

  componentDidMount() { }
  componentWillReceiveProps(nextProps) {
    if (nextProps.modalVisible) {
      try {
        const { match, viewId, type } = this.props;
        const { key, allRangeList } = this.state;
        let currentList = allRangeList;
        let currentKey = key;
        nextProps.currentRegion.list &&
          nextProps.currentRegion.list.length &&
          nextProps.currentRegion.list.map((val, index) => {
            currentKey++;
            let startArray = [];
            let endArray = [];
            if (val.regionAddressType === 3) {
              startArray =
                val.startItems.map(item => [item.areas[0], item.areas[item.areas.length - 1]]) ||
                [];
              endArray =
                val.endItems.map(item => [item.areas[0], item.areas[item.areas.length - 1]]) || [];
            } else {
              startArray = val.startItems.map(item => item.areas);
              endArray = val.endItems.map(item => item.areas);
            }
            this.setState({ key: currentKey });
            const params = {
              viewId,
              type,
              isUpdate: true,
              key: currentKey,
              keyIndex: currentKey,
              currentRegion: {
                startItems: startArray,
                endItems: endArray,
              },
            };
            currentList.push(params);
          });
        this.setState({ allRangeList: currentList, childComponent: [] });
      } catch (error) {
        throw error;
      }
    }
  }

  // 模态框里的增加线路按钮
  addRange = () => {
    const { viewId, type } = this.props;
    const { key, allRangeList } = this.state;
    message.destroy();
    if (allRangeList.length === 1) {
      if (!allRangeList[0]['currentRegion']) {
        message.warning('请先添加上一条范围！');
        return;
      }
    } else if (allRangeList.length > 1) {
      if (!allRangeList[allRangeList.length - 1]['currentRegion']) {
        message.warning('请先添加上一条范围！');
        return;
      }
    }
    let currentKey = key;
    currentKey++;
    let currentList = allRangeList;
    this.setState({ key: currentKey });
    const params = {
      viewId,
      type,
      key: currentKey,
      keyIndex: currentKey,
    };
    currentList.push(params);
    this.setState({ allRangeList: currentList });
  };
  // 模态框里线路后的删除按钮
  removeRange = key => {
    Modal.confirm({
      title: '删除范围',
      content: '确定删除此范围吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const { allRangeList, allRegionArray, childComponent } = this.state;
        let currentList = allRangeList;
        let currentArray = allRegionArray;
        let currentChild = childComponent;
        const idx = childComponent.findIndex(val => val.props.keyIndex === key);
        if (idx > -1) {
          currentChild.splice(idx);
        }
        currentList = currentList.filter(val => val.keyIndex !== key);
        currentArray = currentArray.filter(val => val.keyIndex !== key);
        this.setState({
          allRangeList: currentList,
          allRegionArray: currentArray,
          childComponent: currentChild,
        });
      },
    });
  };

  judgeInArray = (index, arr) => arr.findIndex(val => val.keyIndex === index);

  // 子组件选中起始点后传值给父组件
  handleTempStorage = value => {
    const { allRegionArray, allRangeList, childComponent } = this.state;
    let allArray = allRegionArray;
    let rangArray = [];
    let childArray = [];
    const idx = this.judgeInArray(value.keyIndex, allArray);
    if (idx > -1) {
      allArray[idx] = { ...allArray[idx], ...value };
    } else {
      allArray.push(value);
    }

    allArray.length &&
      allArray.map(val => {
        const params = {
          isUpdate: true,
          keyIndex: val.keyIndex,
          key: val.keyIndex,
          viewId: allRangeList.length && allRangeList[0].viewId,
          type: allRangeList.length && allRangeList[0].type,
          currentRegion: {
            startItems: val.regionItems,
            endItems: val.destinationRegionItems,
          },
        };
        rangArray.push(params);
        const arr = childComponent.filter(
          item => item && item.props && item.props.keyIndex === val.keyIndex
        );
        childArray = [...childArray, ...arr];
      });
    if (allRangeList.length > allRegionArray.length) {
      rangArray[allRangeList.length - 1] = allRangeList[allRangeList.length - 1];
    }
    this.setState({
      allRangeList: rangArray,
      allRegionArray: allArray,
      childComponent: childArray,
    });
  };

  getChildFun() {
    const { childComponent } = this.state;
    let passArray = [];
    childComponent.length &&
      childComponent.map(val => {
        if (val.validateAddress()) {
          passArray.push(0);
        } else {
          passArray.push(1);
        }
      });
    return passArray;
  }
  // 获取子组件
  onRef = ref => {
    const { childComponent } = this.state;
    let array = childComponent;
    array.push(ref);
    this.setState({
      childComponent: array,
    });
  };

  render() {
    const {
      modalVisible,
      form,
      handleAdd,
      handleUpdateModalVisible,
      match,
      viewId,
      type,
    } = this.props;
    const { allRegionArray, allRangeList } = this.state;
    let isAirProduct =
      (viewId === 'product' && type === '1') || (viewId === 'service' && type === 'AIR');
    const Transtype = isAirProduct ? REGION_ADDRESS_TYPE.AIR_PORT : REGION_ADDRESS_TYPE.AREA;
    const okHandle = () => {
      const passFlag = this.getChildFun().every(val => val === 0);
      if (!passFlag) return;
      let params = [];
      if (allRegionArray.length) {
        allRegionArray.map(item => {
          let originItems = [];
          let destinationItems = [];
          originItems = item.regionItems && item.regionItems.map(item => ({ areas: item }));
          destinationItems =
            item.destinationRegionItems &&
            item.destinationRegionItems.map(item => ({ areas: item }));

          params.push({
            startItems: originItems,
            endItems: destinationItems,
            regionAddressType: Transtype,
          });
        });
      }
      handleAdd(params).then(res => {
        if (res.errorCode === 0) {
          message.success('更新成功')
          this.setState({
            allRangeList: [],
            key: 0,
            allRegionArray: [],
          });
        }
      });
    };
    // 模态框里的取消按钮
    const cancelHandle = () => {
      handleUpdateModalVisible();
      this.setState({
        key: 0,
        allRangeList: [],
        allRegionArray: [],
      });
    };

    return (
      <Modal
        width={900}
        maskClosable={false}
        keyboard={false}
        destroyOnClose
        title="编辑范围"
        visible={modalVisible}
        onOk={okHandle}
        onCancel={cancelHandle}
      >
        <Row type="flex" justify="start">
          <Col span={7}>
            <div className={styles.startOrEndStyle}>起点</div>
          </Col>
          <Col span={6} />
          <Col span={7}>
            <div className={styles.startOrEndStyle}>终点</div>
          </Col>
        </Row>
        {allRangeList.length > 0 &&
          allRangeList.map((val, index) => (
            <Row type="flex" justify="start" key={index}>
              <Col span={23}>
                <ProductRangeForm
                  {...val}
                  handleSaveRange={this.handleTempStorage}
                  onRef={this.onRef}
                />
              </Col>
              <Col span={1}>
                <IconButton
                  style={{ position: 'absolute', top: 4 }}
                  title="删除此范围"
                  icon="icon-delete"
                  onClick={() => this.removeRange(val.keyIndex)}
                />
              </Col>
            </Row>
          ))}
        <Row type="flex" justify="center">
          <Form.Item>
            <IconButton icon="icon-add" title="添加范围" onClick={this.addRange} />
          </Form.Item>
        </Row>
      </Modal>
    );
  }
}

@connect(({ service, product, loading }) => ({
  currentService: service.currentService,
  currentProduct: product.currentProduct,
  productRange: product.productRange,
  loading: loading.effects['product/fetchRangeList'],
}))
@Form.create()
class Region extends PureComponent {
  state = {
    formValues: {},
    selectedRows: [],
    modalVisible: false,
    updateModalVisible: false,
    currentRegion: {},
    schemaId: this.props.match.params.id,
  };

  columns = [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: '起点',
      render: (text, record, index) => {
        return (
          <Fragment>
            {record.startItems.map(item => (
              <span style={{ display: 'block' }}>{item.details}</span>
            ))}
          </Fragment>
        );
      },
    },
    {
      title: '终点',
      render: (text, record, index) => {
        return (
          <Fragment>
            {record.endItems.map(item => (
              <span style={{ display: 'block' }}>{item.details}</span>
            ))}
          </Fragment>
        );
      },
    },
  ];

  componentDidMount() {
    this.searchRegions();
  }

  calcIndex = index => {
    const { productRange } = this.props;
    let currentPage = get(productRange, 'pagination.currentPage') || 1;
    let pageSize = get(productRange, 'pagination.pageSize') || 10;
    return (currentPage - 1) * pageSize + index + 1;
  };

  searchRegions = () => {
    const {
      dispatch,
      form,
      location: {
        query: { startSchemaId, endSchemaId },
      },
    } = this.props;
    dispatch({
      type: 'product/fetchRangeList',
      payload: {
        pathParams: {
          startSchemaId,
          endSchemaId,
        },
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleAdd = fieldsValue => {
    const {
      dispatch,
      location: {
        query: { startSchemaId, endSchemaId },
      },
    } = this.props;
    return dispatch({
      type: 'product/addRange',
      payload: {
        data: fieldsValue,
        pathParams: {
          startSchemaId,
          endSchemaId,
        },
      },
    }).then(res => {
      if (res.errorCode === 0) {
        this.handleModalVisible();
        this.handleUpdateModalVisible();
        this.searchRegions();
      }
      return res;
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = flag => {
    this.setState({
      updateModalVisible: !!flag,
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      productRange,
      loading,
      location,
      match,
      currentService,
      currentProduct,
    } = this.props;
    const { modalVisible, updateModalVisible, currentRegion, selectedRows } = this.state;

    let viewId = location.query.viewId;
    let entry = location.query.entry;
    let type = location.query.type;
    let isInner = ['service', 'product'].includes(viewId);

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      schemaId: match.params.id,
      viewId,
      type,
    };
    const updateProps = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleAdd: this.handleAdd,
      currentRegion: productRange,
      schemaId: match.params.id,
      viewId,
      type,
    };
    let bodyStyle = {};
    if (isInner) {
      bodyStyle.padding = 0;
    }

    let isServiceDraft =
      viewId === 'service' &&
      (currentService.status === SERVICE_STATUS.DRAFT ||
        (!currentService.isOnline &&
          currentService.status === SERVICE_STATUS.AUDITTED &&
          entry === 'audit'));
    let isProductDraft =
      viewId === 'product' &&
      (currentProduct.status === SERVICE_STATUS.DRAFT ||
        (!currentProduct.isOnline &&
          currentProduct.status === SERVICE_STATUS.AUDITTED &&
          entry === 'audit'));

    let isShowOperator = isServiceDraft || isProductDraft || viewId === 'region';
    return (
      <Fragment>
        {!isInner && (
          <PageHeaderWrapper
            title="返回"
            backRoute="/base/region"
            wrapperClassName="hiddenContent"
          />
        )}
        <Card bordered={false} style={{ marginTop: 20 }} bodyStyle={bodyStyle}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm} />
            {isShowOperator && (
              <div className={styles.tableListOperator}>
                {productRange &&
                  productRange.list &&
                  currentService.typeCode !== 'ST004' &&
                  productRange.list.length === 0 && (
                    <IconButton icon="icon-add" title="添加" onClick={this.handleModalVisible} />
                  )}
                {productRange &&
                  productRange.list &&
                  productRange.list.length > 0 &&
                  currentService.typeCode !== 'ST004' && (
                    <IconButton
                      icon="icon-edit"
                      title="编辑"
                      onClick={() => this.handleUpdateModalVisible(true)}
                    />
                  )}
              </div>
            )}
            <StandardTable
              rowKey="id"
              pagination={false}
              loading={loading}
              data={productRange}
              columns={this.columns}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
        <UpdateForm {...updateProps} modalVisible={updateModalVisible} />
      </Fragment>
    );
  }
}

export default Region;
